<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search 
          v-model="searchText" 
          placeholder="请输入搜索关键词"
          show-action
          @search="onSearch(searchText)"
          @cancel="onCancel"
          @focus="isResultShow = false"
      />
    </form>
          <!-- 搜索结果 -->
    <search-result v-if="isResultShow"
                   :search-text="searchText"/>
      
          <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText"
                       :search-text="searchText"
                       @search="onSearch"/>
  
          <!-- 历史记录 -->
    <search-history v-else
                    :search-histories="searchHistories"
                    @search="onSearch"
                    @update-histories="searchHistories = $event"/>




  </div>
</template>

<script>
import SearchSuggestion from './components/search-suggestion.vue'
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import {setItem, getItem} from '@/utils/storage'

export default {
  data() {
    return {
      searchText:'',
      isResultShow:false,
      searchHistories:getItem('search-histories') || []
    }
  },
  components:{
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },
  watch:{
    searchHistories(){
      setItem('search-histories', this.searchHistories)
    }
  },
  methods: {
    onSearch(searchText){ 
      this.searchText = searchText
      const index =this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(searchText)


      this.isResultShow = true
    },
    onCancel(){
      this.$router.back()
    }
  },
}
</script>

<style lang="less" scoped>

</style>

</style>